<template>
    <div class="step-list-comp">
        <Step @deleteStep="deleteStep"
              @moveBottom="moveBottom"
              @moveTop="moveTop"
              @addStep="addStep"
              v-for="(item,index) in steps"
              :key="index"
              :step="item"/>
    </div>
</template>

<script>
    import Step from "./Step";

    export default {
        name: 'StepList',
        data() {
            return {};
        },
        props: {
            steps: {
                type: Array
            }
        },
        methods: {
            addStep(step) {
                if (this.steps.length > 19) {
                    this.msgWarn("最多可设置" + 20 + "个步骤")
                    return
                }
                let obj = {
                    index: Math.round(Math.random() * 10000),
                    desc: "",
                    picture: {}
                }
                this.steps.splice(step.index + 1, 0, obj);
                //重新设置id
                let len = this.steps.length
                for (let i = 0; i < len; i++) {
                    this.steps[i].index = i
                }
            },
            deleteStep(step) {
                // 至少要写三步
                if (this.steps.length <= 1) {
                    console.log(1)
                    this.msgWarn("至少要填写一步")
                    return
                }
                this.steps.splice(step.index, 1)
            },
            moveTop(step) {
                if (step.index == 0) {
                    this.msgError("不能再上移了")
                    return
                }
                let index = step.index

                this.steps[index].index--
                this.steps[index - 1].index++
                this.swapArray(this.steps, index - 1, index)
            },
            moveBottom(step) {
                if (step.index == this.steps.length - 1) {
                    this.msgError("不能再下移了")
                    return
                }
                let index = step.index
                this.steps[index].index++
                this.steps[index + 1].index--
                this.swapArray(this.steps, index + 1, index)
            },
            swapArray(arr, index1, index2) {
                arr[index1] = arr.splice(index2, 1, arr[index1])[0];

                let len = this.steps.length
                for (let i = 0; i < len; i++) {
                    this.steps[i].index = i
                }

                return arr;
            }
        },
        mounted() {
        },
        components: {
            Step
        }
    }
</script>

<style scoped lang='less'>
    .step-list-comp {

    }
</style>